package com.zhima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhima.constant.QuestionRedisConstant;
import com.zhima.entity.OjUserQuestion;
import com.zhima.enums.QuestionDifficulty;
import com.zhima.enums.UserQuestionState;
import com.zhima.mapper.OjUserQuestionMapper;
import com.zhima.service.OjQuestionService;
import com.zhima.service.OjUserQuestionService;
import com.zhima.util.PageUtil;
import com.zhima.vo.SimpleQuestionVO;
import com.zhima.vo.UserQuestionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhima
 * @since 2023-08-25
 */
@Service
public class OjUserQuestionServiceImpl extends ServiceImpl<OjUserQuestionMapper, OjUserQuestion> implements OjUserQuestionService {

    @Autowired
    private OjQuestionService ojQuestionService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Page<UserQuestionVO> pageQueryUserQuestion(Long userId, Long pageNum, Long pageSize) {
        Page<OjUserQuestion> pageQueryResult = page(new Page<>(pageNum - 1, pageSize), new LambdaQueryWrapper<OjUserQuestion>().eq(OjUserQuestion::getUserId, userId));
        // 组装基本信息
        List<SimpleQuestionVO> simpleQuestions = ojQuestionService.batchQuerySimpleQuestionByIds(pageQueryResult.getRecords().stream().map(OjUserQuestion::getId).collect(Collectors.toList()));
        List<UserQuestionVO> userQuestionVOS = new ArrayList<>();
        for (int i = 0; i < pageQueryResult.getRecords().size(); i++) {
            OjUserQuestion ojUserQuestion = pageQueryResult.getRecords().get(i);
            UserQuestionVO userQuestionVO = BeanUtil.copyProperties(ojUserQuestion, UserQuestionVO.class);
            userQuestionVO.setQuestion(simpleQuestions.get(i));
            userQuestionVOS.add(userQuestionVO);
        }
        return PageUtil.buildPage(pageQueryResult, userQuestionVOS);
    }

    @Override
    public boolean addUserQuestion(Long userId, Long questionId, UserQuestionState userQuestionState) {
        OjUserQuestion ojUserQuestion = lambdaQuery().eq(OjUserQuestion::getQuestionId, questionId).eq(OjUserQuestion::getUserId, userId).select(OjUserQuestion::getAc).one();
        // 查询不到指定用户本题提交过
        if (ojUserQuestion == null) {
            // 初始化
            ojUserQuestion = new OjUserQuestion();
            ojUserQuestion.setUserId(userId);
            ojUserQuestion.setQuestionId(questionId);
            ojUserQuestion.setAc(userQuestionState);
            ojUserQuestion.setSubmitNum(0);
            ojUserQuestion.setAcNum(0);
        }
        // 上一次提交时间就是现在
        ojUserQuestion.setLastSubmitTime(new Date());
        // 本来是错的才可以更新
        // WA -> WA、AC
        // AC -> end
        if (ojUserQuestion.getAc() == UserQuestionState.WA) {
            ojUserQuestion.setAc(userQuestionState);
        } else {
            // 增加AC次数
            ojUserQuestion.setAcNum(ojUserQuestion.getAcNum() + 1);
        }
        // 增加提交次数
        ojUserQuestion.setSubmitNum(ojUserQuestion.getSubmitNum() + 1);
        return saveOrUpdate(ojUserQuestion);
    }

    @Override
    public Map<String, List<SimpleQuestionVO>> getAcQuestions(Long userId) {
        Map<String, List<SimpleQuestionVO>> acQuestionMap = new HashMap<>();
        for (QuestionDifficulty difficulty : QuestionDifficulty.values()) {
            // 将题目组装后按照题目难度放入map
            Set<String> members = stringRedisTemplate.opsForSet().members(QuestionRedisConstant.QUESTION_USER_AC_PREFIX + userId + ":" + difficulty.getDifficulty());
            if (members == null || members.isEmpty()) {
                acQuestionMap.put(difficulty.getDifficulty(), Collections.emptyList());
                continue;
            }
            acQuestionMap.put(
                    difficulty.getDifficulty(),
                    ojQuestionService.batchQuerySimpleQuestionByIds(
                            members.stream()
                                    .map(Long::parseLong)
                                    .collect(Collectors.toList())
                    )
            );
        }
        return acQuestionMap;
    }
}
